package com.obelisco.modelo.dao.hibernate;

import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;

import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;

import com.obelisco.exception.ObeliscoException;
import com.obelisco.modelo.dao.ITransaccionPreferidaDAO;
import com.obelisco.modelo.data.TransaccionPreferida;

public class TransaccionPreferidaDAO extends HibernateDAO implements ITransaccionPreferidaDAO {

	public TransaccionPreferida findByPK(Serializable clave) {
		try {
        	TransaccionPreferida data = (TransaccionPreferida) getHibernateTemplate().load(TransaccionPreferida.class,clave);
			return data.getEstado().equals("B") ?  null : data;        	
        } catch (RuntimeException re) {
            throw re;
        }		
	}
 
	public List loadAll() {
		try {
			List lista = getHibernateTemplate().find(
			"from TransaccionPreferida operacion where operacion.estado != 'B'");
			return lista;	
        } catch (RuntimeException re) {
            throw re;
        }		
	}

	public void delete(TransaccionPreferida operacion) {
		// TODO Auto-generated method stub
		getHibernateTemplate().delete(operacion);
	}
	
	ClassValidator operacionValidator = new ClassValidator(TransaccionPreferida.class,ResourceBundle.getBundle("com.obelisco.modelo.data.hibernate-validator"));
	
	public void validate(TransaccionPreferida objeto) {

		InvalidValue[] validationMessages =  operacionValidator.getInvalidValues(objeto);

		StringBuffer errores = new StringBuffer();
		for (int i = 0; i < validationMessages.length; i++) {
			InvalidValue value = validationMessages[i];
			errores.append(value.getPropertyName() + " - "+ value.getMessage() + "<br/>");
		}

		if (errores.length() > 0) {
			
			throw new ObeliscoException(errores.toString());
		}

	}


	public void save(TransaccionPreferida objeto) {
		// TODO Auto-generated method stub
		validate(objeto);
		try {
			getHibernateTemplate().saveOrUpdate(objeto);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		// TODO Auto-generated method stub
		try {
			String queryString = "from TransaccionPreferida as modelo where modelo."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			throw re;
		}
	}

}
